//
//  HomePageC.m
//  GuiJuWo
//
//  Created by chenguibang on 16/3/24.
//  Copyright © 2016年 chenguibang. All rights reserved.
//

#import "HomePageC.h"
#import "GBWebViewVM.h"
#import "GBNetTool.h"
#import "GJWBaseRequest.h"
#import "HomeRequstModel.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "GBHudUtil.h"
#import "MJRefresh.h"
#import "MJRefreshHeader.h"
#import "UIScrollView+MJRefresh.h"

@interface HomePageC ()<UIWebViewDelegate,GBWebViewProgressDelegate,UISearchBarDelegate,UIScrollViewDelegate>

@end

@implementation HomePageC

- (void)viewDidLoad {
    [super viewDidLoad];
 
    [RACObserve(self, baseurl) subscribeNext:^(id x) {
        [self.webViewVM loadUrlOnPost:self.baseurl];
    }];
    
    [RACObserve(self.webViewVM, requst) subscribeNext:^(id x) {
        [self.gbWebView loadRequest:self.webViewVM.requst];
    }];

    
    
    self.gbWebView.scrollView.delegate = self;
    
    self.navBar.homeSearchBar.searchBar.placeholder = @"填写相关商品名称或关键词";
    self.navBar.homeSearchBar.searchBar.delegate = self;
    [[self.navBar.homeSearchBar.shareBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        //1、创建分享参数
        NSArray* imageArray = @[@"http://mob.com/Assets/images/logo.png?v=20150320"];
        if (imageArray) {
            
            NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
            [shareParams SSDKSetupShareParamsByText:@"分享内容"
                                             images:imageArray
                                                url:[NSURL URLWithString:@"http://mob.com"]
                                              title:@"分享标题"
                                               type:SSDKContentTypeAuto];
            
            
            
            //2、分享（可以弹出我们的分享菜单和编辑界面）
            [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                                     items:nil
                               shareParams:shareParams
                       onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                           
                           switch (state) {
                               case SSDKResponseStateSuccess:
                               {
                                   UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                       message:nil
                                                                                      delegate:nil
                                                                             cancelButtonTitle:@"确定"
                                                                             otherButtonTitles:nil];
                                   [alertView show];
                                   break;
                               }
                               case SSDKResponseStateFail:
                               {
                                   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                                   message:[NSString stringWithFormat:@"%@",error]
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"OK"
                                                                         otherButtonTitles:nil, nil];
                                   [alert show];
                                   break;
                               }
                               default:
                                   break;
                           }
                       }  
             ];}
    }];
    
    
    [[self.navBar.homeSearchBar.backBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
         [self.view endEditing:YES];
        if ([self.gbWebView canGoBack]) {
            [self.gbWebView goBack];
           
        }
    }];
    
   
    [[self rac_signalForSelector:@selector(searchBar:textDidChange:)] subscribeNext:^(id x) {
        NSLog(@"%@",self.navBar.homeSearchBar.searchBar.text);
    }];
    
    
    
    
    self.gbWebView.scrollView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            // 结束刷新
//            
//            
//           
//        });
        
        [self.gbWebView reload];
        [self.gbWebView.scrollView.mj_header endRefreshing];
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(GBWebView *)gbWebView{
    if (!_gbWebView) {
        _gbWebView = [[GBWebView alloc]init];;
        [self.contentView addSubview:_gbWebView];
//        _gbWebView.backgroundColor = UIColorWithRandom;
        _gbWebView.sd_layout.leftEqualToView(self.contentView).topEqualToView(self.contentView).rightEqualToView(self.contentView).bottomEqualToView(self.contentView);
        _gbWebView.delegate = self;
        _gbWebView.progressDelegate = self;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    return _gbWebView;
}


-(UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];
        [self.gbWebView addSubview:_progressView];
        _progressView.sd_layout.leftEqualToView(self.gbWebView).rightEqualToView(self.gbWebView).topEqualToView(self.gbWebView).autoHeightRatio(0);
    }
    return _progressView;
}

-(GBWebViewVM *)webViewVM{
    if (!_webViewVM) {
        _webViewVM = [[GBWebViewVM alloc]init];
    }
    return _webViewVM;
}

#pragma mark - UIWebViewDelegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

    
    
    return YES;
}
-(void)webViewDidStartLoad:(UIWebView *)webView{
    self.progressView.hidden = NO;
    [self.progressView setProgress:0 animated:NO];
    [GBHudUtil showHud:@"加载中..."];
    
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    self.progressView.hidden = YES;
    [GBHudUtil hideHud];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    self.progressView.hidden = YES;
    [GBHudUtil hideHud];
}
#pragma mark -GBWebViewDelegate
-(void)webView:(GBWebView *)webView didReceiveResourceNumber:(int)resourceNumber totalResources:(int)totalResources
{
    [self.progressView setProgress:resourceNumber/totalResources animated:YES];
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    self.navBar.homeSearchBar.onSearching = YES;
    return YES;
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    self.navBar.homeSearchBar.onSearching = NO;
}

-(void)viewTapped:(UITapGestureRecognizer*)tap1
{
    
    
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//    [self.view endEditing:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [GBHudUtil hideHud];
}

@end
